package com.smartHome.mapper;

import com.smartHome.pojo.entity.Device;
import org.apache.ibatis.annotations.*;

import java.math.BigDecimal;
import java.util.List;

@Mapper
public interface DeviceMapper {
    // 查询指定房间的设备总数
    @Select("SELECT COUNT(*) FROM devices WHERE room_id = #{roomId}")
    int countByRoomId(int roomId);

    // 查询指定房间的在线设备数
    @Select("SELECT COUNT(*) FROM devices WHERE room_id = #{roomId} AND status = 1")
    int countOnlineByRoomId(int roomId);

    @Insert("INSERT into devices (room_id,device_name,status,numerical,pattern,create_time,update_time) values " +
            "(#{roomId},#{deviceName},0,#{numerical},#{pattern},now(),now())")
    void addDevice(Device device);

    @Delete("delete from devices where device_id = #{deviceId}")
    void delete(Integer deviceId);

    /**
     * 通过房间id查找所有设备
     * 
     * @param roomId
     * @return
     */
    @Select("select * from devices where room_id = #{roomId}")
    List<Device> getDeviceList(Integer roomId);

    @Delete("delete from devices where room_id = #{roomId}")
    void deleteDeviceByRoomId(Integer roomId);

    void update(Device device);

    @Update("UPDATE devices SET status = 0, update_time = NOW() WHERE room_id = #{roomId}")
    void turnOffAllDevices(Integer roomId);

    @Select("select * from devices where device_id = #{deviceId}")
    Device getDevice(Integer deviceId);

    @Select("SELECT * FROM devices")
    List<Device> getAllDevices();

    @Select("SELECT house_id FROM rooms WHERE room_id = #{roomId}")
    Long getHouseIdByRoomId(Integer roomId);

    @Select("SELECT DISTINCT house_id FROM rooms")
    List<Long> getAllHouseIds();

    @Select("SELECT power_rating FROM device_types WHERE type_id = " +
            "(SELECT device_type_id FROM devices WHERE device_id = #{deviceId})")
    BigDecimal getDevicePower(Integer deviceId);

    @Update("UPDATE devices d " +
            "JOIN rooms r ON d.room_id = r.room_id " +
            "SET d.status = #{status} " +
            "WHERE r.house_id = #{houseId}")
    void updateStatusByHouseId(@Param("houseId") Integer houseId, @Param("status") Integer status);


    @Update("update devices set status = #{status} where device_id = #{deviceId}")
    void updateByScene(@Param("deviceId") Integer deviceId,@Param("status") Integer status);
}
